use riscv::register::sstatus::{self, SPP, Sstatus};

/// Trap Context
#[repr(C)]
pub struct TrapContext {
    /// general regs[0..31] 32个通用寄存器
    pub x: [usize; 32],
    /// CSR sstatus      
    pub sstatus: Sstatus,
    /// CSR sepc
    pub sepc: usize,
}

impl TrapContext {
    /// set stack pointer to x_2 reg (sp)
    pub fn set_sp(&mut self, sp: usize) {
        self.x[2] = sp; //x2（sp寄存器的值）
    }

    pub fn app_init_context(entry: usize, sp: usize) -> Self {
        let mut sstatus = sstatus::read(); // CSR sstatus
        sstatus.set_spp(SPP::User); //previous privilege mode: user mode
        let mut cx = TrapContext {
            x: [0; 32],
            sstatus,
            sepc: entry, //CSR sepc 记录了trap发生时的执行地址
        };
        cx.set_sp(sp);
        cx
    }
}
